Vue.config.devtools = true;

fontSize();
$(window).resize(function(){
	fontSize();
	});
function fontSize(){
	var size;
	var winW=$(window).width();
	if(winW<=750){
		size=Math.round(winW/7.5);
		if(size>55){
			size=55;
			}
	}else{
		size=100;
		}
	$('html').css({
		'font-size':size+'px'
		})
	}

$(function(){
	//--js下拉选择框
	$('.select').each(function(){
		var _this=$(this);
		_this.find('select').change(function(){
			_this.find('span').html($(this).find("option:selected").text());
			})
		});
	//--
});

//--判断是否登录
var u_name = "",
    u_password = "";
function isLoginFun() {
    if(localStorage.isLogin === 'false' || localStorage.isLogin === undefined){
        window.location.href = 'login.html';
    }else{
        u_name = localStorage.loginName;
        u_password = localStorage.loginPassword
    }
}

//--验证码
function Lzm(dom) {
    this.btn = dom.find('a');
    this.time = 60;
    this.intervalTime;

    var that = this;
    this.btn.click(function () {
        var _ = $(this);
        if(_.hasClass('false')) return;
        getPhone(that);
        _.addClass('false');
        that.run();
        that.intervalTime = setInterval(function () {
            that.run()
        },1000)
    });
    this.run = function () {
        that.btn.html(that.time + "s");
        that.time --;
        if(that.time < 0){
            that.reStart()
        }
    };
    this.reStart = function () {
        clearInterval(that.intervalTime);
        that.btn.removeClass('false');
        that.btn.html("发送验证码");
        that.time = 60;
    }
}
var lzm = [];
function lzmFun() {
    $('li.lzm').each(function (i) {
        lzm[i] = new Lzm($(this));
    })
}
function getPhone(dom) {
    var phone = vue.memberInfo.phone,
        type = dom.btn.context.dataset.id,
        data = '{"action":"012001","Tag":{"c_mobile":"' + phone + '","s_type":"' + type + '"}}';
    wsFun(base64_encode(zip(data)), false);
}

function zip(str){
    var binaryString = pako.gzip(str, { to: 'string' });
    return btoa(binaryString);
}
function unzip(b64Data){
    var strData = atob(b64Data);
    var charData = strData.split('').map(function(x){return x.charCodeAt(0);});
    var binData = new Uint8Array(charData);
    var data = pako.inflate(binData);
    strData = String.fromCharCode.apply(null, new Uint16Array(data));
    return strData;
}
function base64_encode(data){
    var str=CryptoJS.enc.Utf8.parse(data);
    var base64=CryptoJS.enc.Base64.stringify(str);
    return base64;
}
function base64_decode(data){
    var words  = CryptoJS.enc.Base64.parse(data);
    return words;
}

var wsStr = '"Ip":"201.1.3.1","Mac":"00-50-56-C0-00-08","Os":"Windows8+","IsSync":false,';
if ("WebSocket" in window){
    var ws = new WebSocket("ws://47.99.120.98:8083");
    var quotationWS = new WebSocket("ws:116.62.125.225:1028");
    var chartWS = new WebSocket("ws:116.62.125.225:1028");
}else{
    window.location.href='http://qq.u2n7e.cn:1026//pages/down';
}
function wsFun(data, tips) {
    if ("WebSocket" in window) {
        if (ws.readyState && ws.readyState === 1) {
            if(tips === undefined || tips === true){
                pageTipsShow();
            }
            ws.send(data);
        }
        ws.onopen = function(){
            ws.send(data);
        };
        ws.onmessage = function (evt) {
            pageTipsHide();
            var result = JSON.parse(evt.data);
            passwordUpdateTips(result);
        };
        ws.onclose = function (evt) {
            console.log("WebSocketClosed");
        };
        ws.onerror = function (evt) {
            console.log("WebSocketError");
        }
    }else{
        alert("您的浏览器不支持 WebSocket!")
    }
}

function passwordUpdateTips(obj) {
    if(obj.Command === '012001') return;//--如果是验证码的返回结果就直接退出，不做提示
    if(obj.Code === "000000" && obj.Command === '005006'){//--持仓记录
        vue.getData(obj.Customerdata, 'ccRecord');
        return
    }
    if(obj.Code === "000000" && obj.Command === '017006'){//--平仓记录
        vue.getData(obj.Customerdata, 'pcRecord');
        return
    }
    if(obj.Code === "000000" && obj.Command === '006005'){//--委托记录
        vue.getData(obj.Customerdata, 'wtRecord');
        return
    }
    if(obj.Code === "000001" && obj.Command === '002014'){//--持仓底部账户信息（验证账户失败）
        window.location.href = 'login.html';
        return
    }
    if(obj.Code === "000000" && obj.Command === '002014'){//--持仓底部账户信息
        vue.getData(obj.Customerdata, 'account');
        return
    }
    if(obj.Code === "000000" && obj.Command === '015001'){//--获取手机区号
        vue.phoneZone = obj.Customerdata;
        return
    }
    if(obj.Code === "000000" && obj.Command === '018001'){//--我的-基本信息
        vue.getData(obj.Customerdata);
        return
    }
    if(obj.Code === "000000" && obj.Command === '018002'){//--我的-登录历史
        vue.loginHistory = obj.Customerdata;
        return
    }
    if(obj.Code === "000000" && obj.Command === '018003'){//--我的-身份认证
        vue.getAuthenticationData(obj.Customerdata);
        return
    }
    if(obj.Code === "000000" && obj.Command === '009006'){//--系统公告
        noticeGetData2(obj.Customerdata);
        return
    }
    if(obj.Code === "000000" && obj.Command === '007001'){//--交易--获取数据
        vue.getData(obj.Customerdata);
        return
    }
    if(obj.Code === "000000" && (obj.Command === '005005' || obj.Command === '006004')){//--交易--下单成功
        vue.tipsLayer = true;
        return
    }
    var dom = $('.pageTips2');
    dom.find('.msg').html(obj.Description);
    dom.addClass('show');
    console.log(obj);
    setTimeout(function () {
        dom.removeClass('show');
        //--登录成功
        if(obj.Code === "000000" && obj.Command === '002007'){
            localStorage.isLogin = true;
            localStorage.loginName = vue.memberInfo.c_loginname;
            localStorage.loginPassword = vue.memberInfo.c_password;
            window.location.href = 'quotation.html';
            return
        }
        //--注册成功，重置登录密码成功
        if(obj.Code === "000000" && (obj.Command === '002016' || obj.Command === '002008')){
            window.location.href = 'login.html';
            return
        }
        if(obj.Code === "000000" && (obj.Command === '002024' || obj.Command === '002025' || obj.Command === '002026' || obj.Command === '002027')){
            //--修改登录密码，修改手机号，修改资金密码，忘记资金密码（并且修改成功后执行）
            vue.pageShow = 'security';
            return
        }
        if(obj.Code === "000000" && obj.Command === '002028'){
            //--身份认证（并且提交成功后执行）
            vue.Authentication.authentication = 1;
            return
        }
        if(obj.Code === "000000" && (obj.Command === '013003' || obj.Command === '013002')){
            //--资金划转，资产兑换（并且提交成功后执行）
            getWalletDataFun();
            getExchangeRecordFun();
            getTransferRecordFun();
            return
        }
        if(obj.Code === "000000" && (obj.Command === '013006' || obj.Command === '013007')){
            //--添加提币地址，确定提现（并且提交成功后执行）
            getForwardFun(vue.forward.currName);
            vue.pageShow.name = "forward";
            return
        }
        if(obj.Code === "000000" && obj.Command === '019001'){
            //--问题反馈（并且提交成功后执行）
            vue.pageShow = "member";
            vue.feedback = {
                "content":"",
                "file":"false",
                "mail":""
            };
            return
        }
    }, 1500)
}

function quotationWSFun(data, position) {
    if ("WebSocket" in window) {
        if(quotationWS.readyState === 3){
            quotationWS = new WebSocket("ws:116.62.125.225:1028");
        }
        if (quotationWS.readyState && quotationWS.readyState === 1) {
            quotationWS.send(data);
        }
        quotationWS.onopen = function(){
            pageTipsShow();
            quotationWS.send(data);
        };
        quotationWS.onmessage = function (evt) {
            pageTipsHide();
            var result = JSON.parse(evt.data);
            if(position === 'position' && result.Code === '000000' && result.Command === '011001'){//--持仓--止赢止损时获取当前行情
                vue.zyzsGetQuotation(result.Customerdata);
                return;
            }
            if(position === 'trade' && result.Code === '000000' && result.Command === '011001'){//--交易--获取当前行情
                vue.getQuotationData(result.Customerdata);
                return;
            }
            if(result.Code === '000000' && result.Command === '011001'){
                vue.getData(result.Customerdata);
                return;
            }
            if(result.Code === '000000' && result.Command === '000002'){
                vue.updateData(result.Customerdata);
                return;
            }
        };
        quotationWS.onclose = function (evt) {
            console.log("WebSocketClosed");
        };
        quotationWS.onerror = function (evt) {
            console.log("WebSocketError");
        }
    }else{
        alert("您的浏览器不支持 WebSocket!")
    }
}

function chartWSFun(data) {//--k线用的
    if ("WebSocket" in window) {
        if(chartWS.readyState === 3){
            chartWS = new WebSocket("ws:116.62.125.225:1028");
        }
        if (chartWS.readyState && chartWS.readyState === 1) {
            chartWS.send(data);
        }
        chartWS.onopen = function(){
            chartWS.send(data);
        };
        chartWS.onmessage = function (evt) {
            var result = JSON.parse(evt.data);
            if(result.Code === '000000' && result.Command === '000001'){//--全量
                chartDataHandle(result.Customerdata);
                return;
            }
            if(result.Code === '000000' && result.Command === '000003'){//--增量
                chartUpdate(result.Customerdata);
                return;
            }
        };
        chartWS.onclose = function (evt) {
            console.log("WebSocketClosed");
        };
        chartWS.onerror = function (evt) {
            console.log("WebSocketError");
        }
    }else{
        alert("您的浏览器不支持 WebSocket!")
    }
}

function pageTips2(text) {
    var dom = $('.pageTips2');
    dom.find('.msg').html(text);
    dom.addClass('show');
    setTimeout(function () {
        dom.removeClass('show');
    },1500)
}

//--获取地址栏参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r != null){
        return unescape(r[2])
    }else{
        return null;
    }
}

function isNumber(val){
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    //var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val)){
        return true;
    }else{
        return false;
    }
}
function numberLen(num, index){
    return num.toFixed(index);
}

function copyFun() {
    var copyBtn = new ClipboardJS('.copyBtn');
    copyBtn.on("success",function(e){
        pageTips2("复制成功");
        $(e.trigger.dataset.clipboardTips).addClass('on');
        setTimeout(function () {
            $(e.trigger.dataset.clipboardTips).removeClass('on');
        }, 2000);
        e.clearSelection();
    });
}

function isRealName(name) {
    var regName =/^[\u4e00-\u9fa5]{2,4}$/;
    if(!regName.test(name)){
        return false
    }else{
        return true
    }
}

function isPhone(phone) {
    var mobileRegex = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/;
    if(mobileRegex.test(phone)){
        return true
        //alert('手机号正确');
    }else{
        return false
        //alert('手机号输入不正确');
    }
}

//--验证身份证
function IdentityCodeValid(code) {
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;

    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
        tip = "身份证号格式错误";
        pass = false;
    }

    else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = false;
    }
    else{
        //18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    //if(!pass) alert(tip);
    return pass;
}

function pageTipsShow() {
    $('.pageTips').addClass('show');
}
function pageTipsHide() {
    $('.pageTips').removeClass('show');
}

//--验证邮箱
function isMail(mail){
    var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    if(mail === ""){
        return false;
    }else if(!reg.test(mail)){
        return false;
    }else{
        return true;
    }
}

//--pageNum分页组件
Vue.component('mycomponent-page',{
    template:'#pageNum',
    props: ['data'],
    data: function () {
        return {
            current:1,
            prev:1,
            next:1,
            showItem:10,
            allpage:10
        }
    },
    computed:{
        pages:function(){
            this.current = this.data.page.no;
            this.prev = this.current - 1;
            this.next = this.current + 1;
            this.allpage = Math.ceil(this.data.page.total/this.data.page.size);
            var pag = [];
            if( this.current < this.showItem ){ //如果当前的激活的项 小于要显示的条数
                //总页数和要显示的条数那个大就显示多少条
                var i = Math.min(this.showItem,this.allpage);
                while(i){
                    pag.unshift(i--);
                }
            }else{ //当前页数大于显示页数了
                var middle = this.current - Math.floor(this.showItem / 2 ),//从哪里开始
                    i = this.showItem;
                if( middle >  (this.allpage - this.showItem) ){
                    middle = (this.allpage - this.showItem) + 1
                }
                while(i--){
                    pag.push( middle++ );
                }
            }
            return pag
        }
    },
    methods:{
        goto:function(index){
            if(index === this.current) return;
            this.current = index;
            //这里可以发送ajax请求
            var page = this.data.page;
            var data = '{"action":"'+vue.currAction+'","Tag":{"c_mobile":"'+ vue.memberPhone +'","l_pagesize":"'+page.size+'","l_pageno":"'+index+'"}}';
            fundWs(base64_encode(data), this.data.name);
        }
    }
});

//--验证上传图片
function isImgUpload(img) {
    var name = event.target.files[0].name,
        size = event.target.files[0].size;
    var imgExt = name.substr(name.lastIndexOf(".")).toLowerCase();
    if(imgExt !== ".jpg" && imgExt !== ".jpeg" && imgExt !== ".png"){
        alert("请上传jpg格式图片");
        return false
    }else{
        return true
    }
}

function stringReplace(g, t, str) {
    var reg = new RegExp(g, "g");
    var newstr = str.replace(reg, t);
    return newstr;
}

//--获取操作系统版本
function getOS() {
    var sUserAgent = navigator.userAgent;
    var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
    var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
    if (isMac) return "Mac";
    var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
    if (isUnix) return "Unix";
    var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
    if (isLinux) return "Linux";
    if (isWin) {
        var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
        if (isWin2K) return "Win2000";
        var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
        if (isWinXP) return "WinXP";
        var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
        if (isWin2003) return "Win2003";
        var isWinVista= sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
        if (isWinVista) return "WinVista";
        var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
        if (isWin7) return "Win7";
    }
    console.log(navigator);
    return "other";
}

//--获取系统消息
function noticeGetData() {
    var data = '{"Action":"009006",'+wsStr+'"Tag":{"c_loginname":"'+u_name+'"},"SerializString":null}';
    wsFun(base64_encode(zip(data)), false);
}
function noticeGetData2(data) {
    if(localStorage.qqexNoticeRead === undefined){
        localStorage.qqexNoticeRead = JSON.stringify([])
    }
    var read = JSON.parse(localStorage.qqexNoticeRead);
    var readNew = [];
    for(var i=0; i<read.length; i++){
        for(var j=0; j<data.length; j++){
            if(read[i] === data[j].Id){
                readNew.push(read[i]);
                break;
            }
        }
    }
    localStorage.qqexNoticeRead = JSON.stringify(readNew);
    vue.memberHeadMsg = data.length - readNew.length;
    localStorage.qqexNotice = JSON.stringify(data);
}

